import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权

const whiteList = ['/login', '/Register'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start()
  // debugger
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else if (to.path === '/chooseShop') {
      next()
    } else {
      // debugger
      if (store.getters.roleSelf === 'master') {
        next()
      } else if (store.getters.menuList.length === 0) {
        // debugger
        store.dispatch('GetInfo').then(() => { // 拉取用户信息
          next()
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            Message.error('验证失败,请重新登录')
            store.dispatch('LogOut').then(() => {
              // location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          })
        })
      } else {
        next()
      }
      // next()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
